package com.ly.mpayment.rest.up.huisutong;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.net.URLDecoder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
@Path("huisutong")
public class HuiSuTongRest {
    Logger logger = Logger.getLogger(HuiSuTongRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @POST
    public String callBack(@QueryParam("agent_id") String agent_id,@QueryParam("bill_id") String bill_id,
                           @QueryParam("jnet_bill_no") String jnet_bill_no
    ,@QueryParam("par_price") String par_price,@QueryParam("purchase_amt") String purchase_amt,
                           @QueryParam("bill_charge_time") String bill_charge_time
    ,@QueryParam("bill_status") String bill_status,@QueryParam("bill_data_info") String bill_data_info,
                           @QueryParam("sign") String sign,@QueryParam("cardsn") String cardsn) {
        logger.info("huisutong_callback:" + bill_id+",bill_status:"+URLDecoder.decode(bill_status)+","+cardsn);
        if (!StringUtils.isBlank(bill_id)) {
            UpOrder order = upOrderService.findById(bill_id);
            if(order == null){
                logger.info("订单不存在:"+bill_id);
                return "订单不存在";
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+bill_id);
                return "failt";
            }
            if(!sign.equalsIgnoreCase("")){
                logger.info("签名错误:"+sign);
                //return "failt";
            }

            bill_status = URLDecoder.decode(bill_status);
            if (order != null && bill_status.equals("成功") && order.getStatus() == Config.status[0]) {
                order.setRemark(cardsn != null ? cardsn : jnet_bill_no == null ? "" : jnet_bill_no);
                RechargeRest.successUpOrder.add(order);
                return "OK";
            } else if (order != null && order.getStatus() == Config.status[0] && bill_status.equals("失败")) {
                order.setRemark(URLDecoder.decode(bill_data_info));
                RechargeRest.failtUpOrder.add(order);
                return "OK";
            } else {
                this.upOrderService.addOrderMsg(order,URLDecoder.decode(bill_data_info));
                logger.info("huisutong_not_found_order:" + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("agent_id", shop.getAppId());
        data.put("bill_id", order.getUporderuuid());
        data.put("bill_time", new DateUtils().toTimeStamp());
        data.put("supply_type", 1);
        data.put("supply_id",1);
        data.put("charge_type", 0);
        data.put("product_code", order.getUpShopPro().getProductCode());
        data.put("par_price", order.getUpShopPro().getUpfacevalue());
        data.put("product_num",1);
        data.put("region_id","-1");
        data.put("server_id","-1");
        data.put("charge_account", order.getUpphonenum());
        data.put("charge_amt", order.getUpShopPro().getUpfacevalue());
        //填写我方ip
        data.put("client_ip", shop.getUpshopip());
        data.put("notify_url", shop.getOrderCallAddress());
        data.put("time_stamp", new DateUtils().toTimeStamp());
        //运营商类型，联通-lt 移动-yd 电信-dx,不参与验证，必填
        //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
        //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
        //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
        data.put("operator", order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "1" :
                order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "2" :
                        order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "3" : "4");
        //agent_id=***&bill_id=***&bill_time=***&supply_type=***&supply_id=***&product_code=***&product_num=***&region_id=***&server_id=***&charge_account=***&time_stamp=***|||md5Key
        data.put("sign", MD5.md5("agent_id="+ shop.getAppId()+"&bill_id="+
                 order.getUporderuuid()+
                "&bill_time="+data.getString("bill_time")+"&supply_type=1"+
                "&supply_id=1"+"&product_code="+data.getString("product_code")+
                "&product_num=1"+
                "&region_id=-1&server_id=-1"+
                "&charge_account="+order.getUpphonenum()+
                "&time_stamp="+data.getString("bill_time")+
                ("|||"+shop.getUpkey())));

        String result = HttpClient.httpGetUrl(shop.getOrderCommitAddress()+"?"+StringSort.jsonToString(data));
        logger.info("commitOrder_huisutong:" + result + ":" + StringSort.jsonToString(data));
        if (!StringUtils.isBlank(result)) {
            try{
                MultiMap multiMap = Util.parceString(result);
                if (multiMap.containsKey("ret_code") && multiMap.getString("ret_code").equals("0")) {
                    this.upOrderService.updateUpOrderMsg(order,multiMap.getString("jnet_bill_no"),multiMap.containsKey("ret_msg") ?
                            multiMap.getString("ret_msg") : "");
                } else if (multiMap.containsKey("ret_code") && errorCode.contains(multiMap.getString("ret_code"))){
                    order.setRemark(multiMap.getString("ret_msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.updateUpOrderArtificial(order, "",multiMap.getString("ret_msg"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrderArtificial(order, "","提单失败,人工");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    Set<String> errorCode = new HashSet<String>(){{
        add("1");
        add("2");
        add("3");
        add("4");
        add("6");
        add("7");
        add("8");
        add("9");
        add("11");
        add("12");
        add("13");
        add("14");
        add("15");
        add("16");
        add("17");
        add("18");
        add("20");
        add("-1");
        add("98");
    }};

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("bill_id", upOrder.getUporderuuid());
        data.put("agent_id", shopInfo.getAppId());
        data.put("time_stamp", new DateUtils().toTimeStamp());
        //agent_id=***&bill_id=***&time_stamp=***|||md5Key
        data.put("sign", MD5.md5("agent_id="+shopInfo.getAppId()+"&bill_id="+upOrder.getUporderuuid()+"&time_stamp="+data.getString("time_stamp")+"|||"+shopInfo.getUpkey()));
        String result = HttpClient.httpGetUrl(shopInfo.getOrderStatusAddress()+"?"+StringSort.jsonToString(data));
        logger.info("huisutongqueryOrder:" + StringSort.jsonToString(data) + ":" + result);
        if (!StringUtils.isBlank(result)) {
            try {
                //充值状态：失败、处理中、成功
                MultiMap multiMap = Util.parceString(URLDecoder.decode(result));
                multiMap.put("ret_msg", URLDecoder.decode(multiMap.getString("ret_msg")));
                if (multiMap.containsKey("ret_code") && multiMap.getString("ret_code").equals("0")) {
                    UpOrder order = upOrderService.findById(multiMap.getString("bill_id"));
                    if (order != null && multiMap.getString("bill_status").equals("成功") && order.getStatus() == Config.status[0]) {
                        order.setRemark( multiMap.containsKey("cardsn") ? multiMap.getString("cardsn") :
                                multiMap.getString("ret_msg"));
                        RechargeRest.successUpOrder.add(order);
                    } else if (order != null && order.getStatus() == Config.status[0] && multiMap.getString("bill_status").equals("失败") ) {
                        order.setRemark(multiMap.getString("ret_msg"));
                        RechargeRest.failtUpOrder.add(order);
                    } else {
                        this.upOrderService.addOrderMsg(order,multiMap.getString("ret_msg"));
                        logger.info("huisutong_not_found_order:" + order.getUpphonenum());
                    }
                } else if(multiMap.getString("ret_code").equals("-1")){
                    UpOrder order = upOrderService.findById(multiMap.getString("bill_id"));
                    order.setRemark(multiMap.getString("ret_msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    logger.info("huisutong_not_found_order:" + upOrder.getUpphonenum());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

